<?php defined('SYSPATH') OR die('No direct access allowed.');

class Auth_Controller extends Controller {

	public function __construct(){
		parent::__construct(); // This must be included
		// Load sessions, to support logins
		$this->session = Session::instance();
	}

	public function index(){
		url::redirect('auth/login');
	}
	
	public function login($error_msg=""){
		$auth = new Auth();
		if($auth->logged_in()){
			url::redirect('painel');
		}
		// Load Captcha library, you can supply the name of the config group you would like to use.
		$captcha = new Captcha;
			
		// Ban bots (that accept session cookies) after 50 invalid responses.
		// Be careful not to ban real people though! Set the threshold high enough.
		if ($captcha->invalid_count() > 49)
			exit('Bye! Stupid bot.');

		$this->create_view('login');
		//$this->view->menu_esq = new View('menu_esq');
		$this->view->cabecalho->title = "Login";
		$this->view->error = $error_msg;
		$this->view->captcha = $captcha->render();
		$this->view->render(TRUE);
	}

	public function logout(){
		$auth = new Auth();
		$auth->logout();
		$this->create_view('logout');
		//$this->view->menu_esq = new View('default/menu_esq');
		$this->view->cabecalho->title = "Logout";
		$this->view->render(TRUE);
	}

	public function auth(){
		//tenta pegar a quantidade de erros salva na sessão, se não houver seta login_errors para 0
		$login_errors = $this->session->get("login_errors", 0);
		if($login_errors>=5){
			// Captcha::valid() is a static method that can be used as a Validation rule also.
			if (!Captcha::valid($this->input->post('captcha_response'))){
				url::redirect('auth/login/'.Kohana::lang('auth.e_captcha'));
			}
		}

		$remenber = $this->input->post('autologin');
		if($remenber=="1"){
			$remenber = true;
		}else{
			$remenber = false;
		}
		$auth = new Auth();
		if($auth->logged_in()){
			url::redirect('painel');
		}else{
			if($auth->login($this->input->post('username'), $this->input->post('password'), $remenber)){
				//usuario logou
				$this->session->delete("login_errors");
				//url::redirect($this->session->get("requested_url")); //return to page where login was called
				url::redirect('painel'); //return to painel page
			}else{
				//usuario errou o login ou a senha
				$login_errors++;
				$this->session->set("login_errors", $login_errors); 
				url::redirect('auth/login/'.Kohana::lang('auth.e_login'));
			}
		}
	}

} // End Welcome Controller